import React, {useEffect, useRef, useState,} from "react";
import {
  ActionType,
  ProColumns, ProFormSelect
} from "@ant-design/pro-components";
import {
  ProTable,
  ProFormText, ModalForm,
} from "@ant-design/pro-components";
import {Button, Popconfirm,} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import {addWarehouse, deleteWarehouse, listWarehouseByPage, updateWarehouse} from "@/services/warehouse/api";
import message from "antd/es/message";
import {listAllManufacturer} from "@/services/manufacturer/api";


const WarehouseControl: React.FC = () => {

  const actionRef = useRef<ActionType>();
  const [currentPage,setCurrentPage] = useState<number>(1);
  const [isCreate, setIsCreate] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.WarehouseVO>();
  const [isUpdate, setIsUpdate] = useState<boolean>(false);
  const [data, setData] = useState<API.WarehouseVO[]>([]);
  const [total, setTotal] = useState<number>(0);
  const loadData = async (params: any) => {
    const res = await listWarehouseByPage({
      params : params,
      pageNum: currentPage,
      pageSize: 10,
    });
    if (res.code != 0) {
      message.error("仓库数据加载失败 " + res.message);
      return;
    }
    setData(res?.data?.records || []);
    setTotal(res?.data?.total || 0);
  }
  const loadManufacturer = async ()=>{
    const res = await listAllManufacturer();
    if(res.code!=0){
      message.error("生产商信息加载失败"+res.message);
      return;
    }
    return (res?.data||[]).map(manufacturer=>({label: manufacturer.name, value: manufacturer.id}));
  }
  const handleDelete=async (id: string)=>{
    const res = await deleteWarehouse(id);
    if(res.code != 0){
      message.error("删除仓库失败 "+res.message);
      return
    }
    message.success("删除仓库成功");
  }
  const columns: ProColumns<API.WarehouseVO>[] = [
    {
      title: '仓库编码',
      width: 120,
      dataIndex: 'warehouseCode',
    },
    {
      title: '仓库名称',
      width: 120,
      dataIndex: 'warehouseName',
    },
    {
      title: '仓库地址',
      width: 120,
      dataIndex: 'address',
    },
    {
      title: '操作',
      width: 120,
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <Button key="edit" onClick={
          ()=>{
            setIsUpdate(true);
            setCurrent(record);
          }
        } type={'primary'}>
          编辑
        </Button>,

          <Popconfirm
            title="你确定要删除仓库吗"
            key="delete"
            onConfirm={()=>{
              handleDelete(record?.id||'');
            }}
            onCancel={()=>{}}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
      ],
    },
  ];

  useEffect(() => {
    loadData({});
  }, [currentPage])
  return (
    <>
      <ProTable<API.WarehouseVO>
        columns={columns}
        request={async (params)=>{
          await loadData(params);

          return data;
        }}
        actionRef={actionRef}
        dataSource={data}
        cardBordered
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: {fixed: 'right', disable: true},
          },
          onChange(value) {},
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 10,
          onChange: (page) => setCurrentPage(page),
          total: total,
        }}
        dateFormatter="string"
        headerTitle="仓库管理"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined/>}
            onClick={() => {
              setIsCreate(true);
            }}
            type="primary"
          >
            新建仓库
          </Button>,

        ]}
      />
      <ModalForm title="添加仓库" open={isCreate}
                 onFinish={async (values: any) => {
                   const res = await addWarehouse(values);
                   if (res.code != 0) {
                     message.error("仓库添加失败 " + res.message);
                   } else {
                     message.success('仓库添加成功');
                     setIsCreate(false);
                   }
                 }}
                 modalProps={{
                   destroyOnClose: true,
                   onCancel: () => setIsCreate(false),
                 }}
                 initialValues={{
                   name: '蚂蚁设计有限公司',
                   useMode: 'chapter',
                 }}
                 autoFocusFirstInput>
        <ProFormText
          required={true}
          name="warehouseName"
          label="仓库名称"
          placeholder="请输入仓库名称"
        />
        <ProFormText
          required={true}
          name="warehouseCode"
          label="仓库编码"
        />
        <ProFormSelect label={'关联生产商'} name={'manufacturerId'} request={loadManufacturer} required={true} />
        <ProFormText
          name="address"
          label="仓库地址"
          placeholder="请输入仓库地址"
        />
      </ModalForm>
      <ModalForm title="修改仓库信息" open={isUpdate}
                 onFinish={async (values: any) => {
                   const res = await updateWarehouse({
                     id: current?.id,
                     warehouseName: values?.warehouseName,
                     address: values?.address,
                   });
                   if (res.code != 0) {
                     message.error("仓库信息更新失败 " + res.message);
                   } else {
                     message.success('仓库信息更新成功');
                     setIsUpdate(false);
                   }
                 }}
                 modalProps={{
                   destroyOnClose: true,
                   onCancel: () => setIsUpdate(false),
                 }}
                 initialValues={current}
                 autoFocusFirstInput>
        <ProFormText
          readonly={true}
          required={true}
          name="warehouseCode"
          label="仓库编码"
        />
        <ProFormText
          name="warehouseName"
          label="仓库名称"
          required={true}
          placeholder="请输入仓库名称"
        />

        <ProFormText
          name="address"
          label="仓库地址"
          placeholder="请输入仓库地址"
        />
      </ModalForm>
    </>
  );
}
export default WarehouseControl;
